package com.myj.jim.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.myj.jim.dao.AuthorityDao;
import com.myj.jim.dao.MenuDao;
import com.myj.jim.dao.RoleDao;
import com.myj.jim.domain.Menu;
import com.myj.jim.domain.RoleAuthority;
import com.myj.jim.domain.ZNodesJson;
import com.myj.jim.service.AuthorityService;

@Service
public class AuthorityServiceImpl implements AuthorityService {

	@Autowired
	private AuthorityDao authorityDao;
	
	@Autowired
	private MenuDao menuDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Override
	public List<ZNodesJson> getAuthorityTreeJson(String roleno) {
		
		List<Menu> pmList = menuDao.selectListByPid(0);//查出父菜单
		List<ZNodesJson> znjList = new ArrayList<ZNodesJson>();
		
		if(roleno!=null && !"".equals(roleno)){
			List<RoleAuthority> raList = roleDao.selectRoleAuthorityByRoleno(roleno);
			Map<String, Object> authMap = toMap(raList);
			
			for(Menu pm : pmList){
				
				List<Menu> cmList = menuDao.selectListByPid(pm.getId());//查出子菜单
				List<ZNodesJson> cZnjList = new ArrayList<ZNodesJson>();//将子菜单转成符合zTree的json格式
				for(Menu cm : cmList){
					ZNodesJson cZnj = new ZNodesJson();
					cZnj.setId(cm.getId());
					cZnj.setName(cm.getMenuname());
					cZnj.setAuthorityNo(cm.getAuthorityno());
					cZnj.setParent(false);
					
					if(authMap.containsKey(cm.getAuthorityno())){
						cZnj.setChecked(true);
					}
					cZnjList.add(cZnj);
				}
				
				ZNodesJson znj = new ZNodesJson();//将父菜单转成符合zTree的json格式
				znj.setId(pm.getId());
				znj.setName(pm.getMenuname());
				znj.setParent(true);
				znj.setOpen(false);
				znj.setChildren(cZnjList);//放入刚转换的子菜单
				znjList.add(znj);
			}
			
		}else{
				for(Menu pm : pmList){
				
				List<Menu> cmList = menuDao.selectListByPid(pm.getId());//查出子菜单
				List<ZNodesJson> cZnjList = new ArrayList<ZNodesJson>();//将子菜单转成符合zTree的json格式
				for(Menu cm : cmList){
					ZNodesJson cZnj = new ZNodesJson();
					cZnj.setId(cm.getId());
					cZnj.setName(cm.getMenuname());
					cZnj.setAuthorityNo(cm.getAuthorityno());
					cZnj.setParent(false);
					cZnjList.add(cZnj);
				}
				
				ZNodesJson znj = new ZNodesJson();//将父菜单转成符合zTree的json格式
				znj.setId(pm.getId());
				znj.setName(pm.getMenuname());
				znj.setParent(true);
				znj.setOpen(false);
				znj.setChildren(cZnjList);//放入刚转换的子菜单
				znjList.add(znj);
			}
		}
		
		
		
		return znjList;
	}

	public Map<String, Object> toMap(List<RoleAuthority> list){
		Map<String, Object> map = new HashMap<String, Object>();
		for(RoleAuthority ra : list){
			map.put(ra.getAuthorityno(), ra.getAuthorityno());
		}
		
		return map;
	}

}
